package demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 请求参数处理
 */
@Controller
@RequestMapping("/request")
public class RequestParameterController {
    // 接收参数 name，参数可选
    @RequestMapping("p1")
    public String p1(String name, Model model) {
        String tip = "参数是可选的，修改URL（/request/p1?name=XXX）中name的值，或去掉?name=XXX，观察结果有什么不同";
        model.addAttribute("tip", tip);
        String msg = String.format("客户端请求 name = %s", name);
        model.addAttribute("msg", msg);
        return "controller/parameter";
    }

    // 必须提供name参数
    @RequestMapping("p2")
    public String p2(@RequestParam String name, Model model) {
        String tip = "参数是必须提供的，修改URL（/request/p2?name=XXX）去掉?name=XXX，观察结果有什么不同";
        model.addAttribute("tip", tip);
        String msg = String.format("客户端请求 name = %s", name);
        model.addAttribute("msg", msg);
        return "controller/parameter";
    }

    // 客户端提供的参数和形参的名称不一样
    @RequestMapping("p3")
    public String p3(@RequestParam("req") String name, Model model) {
        String tip = "URL参数与方法参数数映射，URL参数名是reg，方法参数名是name。";
        model.addAttribute("tip", tip);
        String msg = String.format("客户端请求 name = %s", name);
        model.addAttribute("msg", msg);
        return "controller/parameter";
    }

    // 设定默认值
    @RequestMapping("p4")
    public String p4(@RequestParam(name="req", defaultValue = "p4默认参数") String name, Model model) {
        String tip = "参数有默认值，修改URL（/request/p4?req=XXX）去掉?req=XXX，观察结果有什么不同";
        model.addAttribute("tip", tip);
        String msg = String.format("客户端请求 req = %s", name);
        model.addAttribute("msg", msg);
        return "controller/parameter";
    }

    // 整体参数
    @RequestMapping("p5")
    public String p5(College college, Model model) {
        String tip = "整体接收参数，把多个参数映射到一个对象。";
        model.addAttribute("tip", tip);
        String msg = String.format("客户端请求 %s", college.toString());
        model.addAttribute("msg", msg);
        return "controller/parameter";
    }
}
